import { defineStore } from 'pinia'
import { apiClient } from '@/api/client'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    isLoggedIn: false,
    token: null,
    loading: false,
    error: null
  }),
  
  getters: {
    userInfo: (state) => state.user,
    isAuthenticated: (state) => state.isLoggedIn && state.token
  },
  
  actions: {
    async login(credentials) {
      this.loading = true
      this.error = null
      try {
        const resp = await apiClient.post('/api/auth/login', {
          usernameOrEmail: credentials.usernameOrEmail,
          password: credentials.password
        })
        const token = resp?.token || resp?.data?.token
        if (!token) {
          throw new Error('登录失败')
        }
        this.token = token
        this.isLoggedIn = true
        // 仅保存基本信息（后端未返回用户详情）
        this.user = {
          username: credentials.usernameOrEmail
        }
        // 记住我：true->localStorage；false->sessionStorage
        if (credentials.remember) {
          localStorage.setItem('token', this.token)
        } else {
          sessionStorage.setItem('token', this.token)
        }
        localStorage.setItem('user', JSON.stringify(this.user))
        return { success: true }
      } catch (error) {
        this.error = error.message || '登录失败'
        return { success: false, error: this.error }
      } finally {
        this.loading = false
      }
    },
    
    async register(userData) {
      this.loading = true
      this.error = null
      try {
        const resp = await apiClient.post('/api/users/register', {
          username: userData.username,
          email: userData.email,
          password: userData.password,
          phone: userData.phone,
          realName: userData.name
        })
        const data = resp?.id ? resp : resp?.data
        if (!data?.id) {
          throw new Error('注册失败')
        }
        this.user = {
          id: data.id,
          username: data.username,
          email: data.email,
          phone: data.phone,
          realName: data.realName,
          avatar: data.avatarUrl || '/src/assets/images/default-avatar.svg'
        }
        // 注册不自动登录；受保护接口需登录获取令牌
        this.isLoggedIn = false
        localStorage.setItem('user', JSON.stringify(this.user))
        return { success: true, user: this.user }
      } catch (error) {
        this.error = error.message || '注册失败'
        return { success: false, error: this.error }
      } finally {
        this.loading = false
      }
    },
    
    logout() {
      this.user = null
      this.token = null
      this.isLoggedIn = false
      this.error = null
      
      // 清除localStorage
      localStorage.removeItem('user')
      localStorage.removeItem('token')
      // 清除sessionStorage
      sessionStorage.removeItem('token')
    },
    
    async updateProfile(profileData) {
      this.loading = true
      this.error = null
      
      try {
        // 正常 PUT：后端可能返回 200 + 用户对象，或 204 无内容
        const resp = await (apiClient.put
          ? apiClient.put('/api/users/me', profileData)
          : apiClient.post('/api/users/me?_method=PUT', profileData))

        // 如果后端返回了用户对象，优先使用；否则视为成功并用本地表单合并更新
        const data = resp?.id ? resp : resp?.data
        if (data && data.id) {
          this.user = {
            id: data.id,
            username: data.username,
            email: data.email,
            phone: data.phone,
            realName: data.realName,
            avatar: data.avatarUrl || '/src/assets/images/default-avatar.svg'
          }
        } else {
          // 兼容 204 无内容：不抛错，合并本地表单到现有用户信息
          this.user = {
            ...(this.user || {}),
            username: this.user?.username || profileData.username,
            realName: profileData.realName,
            email: profileData.email,
            phone: profileData.phone,
            avatar: this.user?.avatar || '/src/assets/images/default-avatar.svg'
          }
        }
        localStorage.setItem('user', JSON.stringify(this.user))
        return { success: true, user: this.user }
      } catch (error) {
        this.error = error.message
        return { success: false, error: error.message }
      } finally {
        this.loading = false
      }
    },

    async uploadAvatar(file) {
      this.loading = true
      this.error = null
      try {
        const fd = new FormData()
        fd.append('file', file)
        const resp = await apiClient.postUpload('/api/users/me/avatar', fd)
        const data = resp?.id ? resp : resp?.data
        if (!data || !data.id) {
          throw new Error('上传失败')
        }
        this.user = {
          ...(this.user || {}),
          id: data.id,
          username: data.username,
          email: data.email,
          phone: data.phone,
          realName: data.realName,
          avatar: data.avatarUrl || (this.user?.avatar || '/src/assets/images/default-avatar.svg')
        }
        localStorage.setItem('user', JSON.stringify(this.user))
        return { success: true, user: this.user }
      } catch (error) {
        this.error = error.message || '上传失败'
        return { success: false, error: this.error }
      } finally {
        this.loading = false
      }
    },
    
    initUser() {
      // 从localStorage初始化用户信息
      const savedUser = localStorage.getItem('user')
      const savedToken = sessionStorage.getItem('token') || localStorage.getItem('token')
      
      if (savedUser && savedToken) {
        try {
          this.user = JSON.parse(savedUser)
          this.token = savedToken
          this.isLoggedIn = true
        } catch (error) {
          console.error('解析用户数据失败:', error)
          this.logout()
        }
      }
    }
    ,
    async fetchProfile() {
      this.loading = true
      this.error = null
      try {
        const resp = await apiClient.get('/api/users/me')
        const data = resp?.id ? resp : resp?.data
        if (!data || !data.id) {
          throw new Error('查询失败')
        }
        this.user = {
          id: data.id,
          username: data.username,
          email: data.email,
          phone: data.phone,
          realName: data.realName,
          avatar: data.avatarUrl || '/src/assets/images/default-avatar.svg'
        }
        this.isLoggedIn = !!(sessionStorage.getItem('token') || localStorage.getItem('token'))
        localStorage.setItem('user', JSON.stringify(this.user))
        return { success: true, user: this.user }
      } catch (error) {
        this.error = error.message || '查询失败'
        return { success: false, error: this.error }
      } finally {
        this.loading = false
      }
    }
  }
})